package com.kk.xhr.model.dao.custom;

import com.kk.xhr.model.dto.PermissionTreeDTO;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;

import java.util.Set;

/**
 * 自定义部门mapper
 *
 * @author kkmystery
 * @version 1.0 2021/3/4
 * @since 1.0.0
 */
@Mapper
public interface PermissionCustomMapper {

    /**
     * 根据用户id连接查询拥有的权限
     *
     * @param userId 用户id
     * @return 权限列表
     */
    @Select("select p.path from permission p" +
        "left join role_permission rp on p.id = rp.permission_id" +
        "left join user_role ur on ur.role_id = rp.role_id" +
        "left join role r on r.id = ur.role_id" +
        "where ur.user_id = #{userId} and r.status = 1 and p.status = 1")
    Set<String> queryPermsByUserId(@Param("userId") Long userId);

    /**
     * 根据id查询权限以及子权限
     *
     * @param id 主键id
     * @return PermissionTreeDTO
     */
    @Select("select * from permission where pid = #{id} and status = 1")
    @Results(id = "PermissionTreeMap", value = {
        @Result(id = true, property = "id", column = "id"),
        @Result(property = "pid", column = "pid"),
        @Result(property = "name", column = "name"),
        @Result(property = "component", column = "component"),
        @Result(property = "path", column = "path"),
        @Result(property = "title", column = "title"),
        @Result(property = "icon", column = "icon"),
        @Result(property = "hidden", column = "hidden"),
        @Result(property = "children", column = "id",
            many = @Many(select = "com.kk.xhr.model.dao.custom.PermissionCustomMapper.query",
                fetchType = FetchType.EAGER)),
    })
    PermissionTreeDTO query(@Param("id") Long id);
}
